Page({
  request: {},
  data: {
    formData: {
      orderCctName: "",
      orderCctMobile: "",
      topCatId: "",
      svrId: "",
      items: []
    },
    orderItemIdSuffix: 1,
    orderItemList: [],
    svrList: [],
    subCatList: [],
    topCatList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.request = require('../../common/networks');
    this.util = require('../../common/util');

    var cct = wx.getStorageSync("cct");
    if (!!cct) {
      this.setData({
        "formData.orderCctName": cct.cctName,
        "formData.orderCctMobile": cct.cctMobile
      })
    }
    wx.showLoading({
      title: '数据加载中...',
      mask: true
    })
    let page = this;
    this.request.getTopCatAndSvrs({}, function(data) {
      page.setData({
        topCatList: data
      });
      wx.hideLoading();
    }, function() {
      wx.showToast({
        title: 'Sorry，数据加载失败，请刷新重试',
        icon: 'none',
        duration: 3000
      })
      wx.hideLoading();
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    wx.setNavigationBarTitle({
      title: '蒲公英家居-创建新订单',
    })
  },
  bindCctNameInput: function(e) {
    this.data.formData.orderCctName = e.detail.value;
  },
  bindCctMobileInput: function(e) {
    this.data.formData.orderCctMobile = e.detail.value;
  },
  bindTopCatClick: function(e) {
    var page = this;
    var current = page.data.topCatList[e.currentTarget.dataset.index];
    var selected = !current.selected;

    var unselect = function() {
      page.data.topCatList.forEach(function(topCat) {
        topCat.selected = topCat.hide = false;
      });

      page.setData({
        svrList: [],
        orderItemList: [],
        topCatList: page.data.topCatList,
        orderItemData: [],
        "formData.svrId": "",
        "formData.topCatId": "",
        "formData.items": [],
        subCatList: page.util.emptyMultiArray()
      });
    }

    var select = function(current) {
      page.data.topCatList.forEach(function(topCat) {
        var isCurrent = topCat.id == current.id
        topCat.selected = isCurrent;
        topCat.hide = !isCurrent;
      });

      current.svrList.forEach(function(child) {
        child.selected = child.hide = false;
      });

      page.setData({
        svrList: current.svrList,
        topCatList: page.data.topCatList,
        "formData.topCatId": current.id
      });

      var requestParams = {};
      requestParams.parentId = current.id;
      page.request.getCategoryTree(requestParams, function(subCatList) {
        page.data.subCatList = subCatList || page.util.emptyMultiArray();
      }, function() {
        page.data.subCatList = page.util.emptyMultiArray();
      })
    }

    if (!selected) {
      if (this.data.orderItemList.length > 0) {
        wx.showModal({
          title: '提示',
          content: '更改服务类型将会清空所有商品信息，确定么？',
          success: function(e) {
            if (e.cancel) {
              return;
            }
            unselect();
          }
        })
      } else {
        unselect();
      }
    } else {
      select(current);
    }
  },
  onSvrClick: function(e) {
    var list = this.data.svrList;
    var current = list[e.currentTarget.dataset.index];
    var svrId = "";
    for (var i in list) {
      var svr = list[i];
      if (svr.id == current.id) {
        if (svr.selected) {
          return;
        }

        svr.selected = true;
        svrId = svr.id;
      } else {
        svr.selected = false;
      }
    }
    this.setData({
      svrList: list,
      "formData.svrId": svrId
    })
  },
  addOrderItem: function(e) {
    if (!this.data.formData.topCatId) {
      wx.showToast({
        icon: 'none',
        title: '请选择服务类型',
      })
      return;
    }
    if (this.data.formData.items.length >= 20) {
      wx.showToast({
        icon: 'none',
        title: '最多只能添加20个商品',
      })
      return;
    }

    var itemList = this.data.orderItemList;
    var itemDataList = this.data.formData.items;
    var orderItemId = "orderItem_" + this.data.orderItemIdSuffix++;
    var idx = this.data.subCatList[0].isLeaf == '1' ? -1 : 0;
    var newOrderItem = {
      id: orderItemId,
      catList: [this.data.subCatList, this.data.subCatList[0].children],
      catIndexList: [0, 0],
      itemNum: 1
    }
    var newOrderItemData = {
      id: orderItemId,
      itemNum: 1
    }

    itemList.push(newOrderItem);
    itemDataList.push(newOrderItemData);

    this.setData({
      orderItemList: itemList
    });
  },
  onSubCatChange: function(e) {
    var indexList = e.detail.value;
    if (indexList[0] < 0) {
      return;
    }
    var orderItemList = this.data.orderItemList;
    var orderItemId = e.currentTarget.dataset.orderItemId;
    var orderItemIndex = this.util.findIndexById(orderItemList, orderItemId);
    var catList = orderItemList[orderItemIndex].catList;
    var catTitle = catList[0][indexList[0]].name;
    var isLeaf = catList[0][indexList[0]].isLeaf == '1';
    if (!isLeaf && indexList[1] < 0) {
      return;
    }
    if (!isLeaf) {
      catTitle += ' / ' + catList[1][indexList[1]].name;
    }

    var orderItemData = this.data.formData.items[orderItemIndex];
    orderItemData.subCatId = catList[0][indexList[0]].id;
    orderItemData.leafCatId = isLeaf ? "" : catList[1][indexList[1]].id;

    var chgval = {}
    var indexKey = 'orderItemList[' + orderItemIndex + '].catIndexList';
    chgval[indexKey] = indexList;

    var titleKey = 'orderItemList[' + orderItemIndex + '].catTitle';
    chgval[titleKey] = catTitle;

    var _titleKey = 'formData.items[' + orderItemIndex + '].catTitle';
    chgval[_titleKey] = catTitle;

    this.setData(chgval);
  },
  onSubCatColumnChange: function(e) {
    if (e.detail.column != 0) {
      return;
    }

    var orderItemList = this.data.orderItemList;
    var orderItemId = e.currentTarget.dataset.orderItemId;
    var orderItemIndex = this.util.findIndexById(orderItemList, orderItemId);
    var catList = this.data.orderItemList[orderItemIndex].catList;
    var index = e.detail.value;
    catList[1] = catList[0][index].children;
    var orderItemList = this.data.orderItemList;
    var val = {};
    var key = 'orderItemList[' + orderItemIndex + '].catList';
    val[key] = catList;
    this.setData(val);
  },
  bindDeleteOrderItem: function(e) {
    var orderItemId = e.currentTarget.dataset.orderItemId;
    var orderItemList = this.data.orderItemList;
    var orderItemIndex = this.util.findIndexById(orderItemList, orderItemId);
    orderItemList.splice(orderItemIndex, 1);
    this.data.formData.items.splice(orderItemIndex, 1);
    this.setData({
      orderItemList: orderItemList
    });
  },
  bindOrderItemTotal: function(e) {
    this.setOrderItemValue(e, "itemNum");
  },
  bindOrderItemLen: function(e) {
    this.setOrderItemValue(e, "length");
  },
  bindOrderItemWidth: function(e) {
    this.setOrderItemValue(e, "width");
  },
  bindOrderItemHeight: function(e) {
    this.setOrderItemValue(e, "height");
  },
  bindOrderItemWeight: function(e) {
    this.setOrderItemValue(e, "weight");
  },
  bindOrderItemRequirements: function(e) {
    this.setOrderItemValue(e, "req");
  },
  bindOrderItemModel: function(e) {
    this.setOrderItemValue(e, "model");
  },
  setOrderItemValue: function(e, key) {
    var orderItemId = e.currentTarget.dataset.orderItemId;
    var orderItemList = this.data.orderItemList;
    var orderItemIndex = this.util.findIndexById(orderItemList, orderItemId);

    orderItemList[orderItemIndex][key] = e.detail.value;
    this.data.formData.items[orderItemIndex][key] = e.detail.value;
  },
  bindNextBtn: function(e) {
    let util = require('../../common/util')
    if (util.isEmpty(this.data.formData.orderCctName)) {
      util.showToast('请输入联系人姓名')
      return
    }

    if (util.isEmpty(this.data.formData.orderCctMobile)) {
      util.showToast('请输入联系人手机号码')
      return
    }

    if (!util.isMobile(this.data.formData.orderCctMobile)) {
      util.showToast('您填写的联系人手机号码是个无效号码');
      return
    }

    if (util.isEmpty(this.data.formData.topCatId)) {
      util.showToast('请选择服务类目')
      return
    }

    if (util.isEmpty(this.data.formData.svrId)) {
      util.showToast('请输入服务类型')
      return
    }

    if (!this.data.formData.items || this.data.formData.items.length <= 0) {
      util.showToast('请添加商品信息')
      return
    }

    var orderItems = this.data.formData.items;
    for (var i = 0; i < orderItems.length; ++i) {
      var item = orderItems[i];
      if (util.isEmpty(item.catTitle)) {
        util.showToast('请选择商品类别')
        return
      }
      if (util.isEmpty(item.itemNum) || parseInt(item.itemNum) == NaN) {
        util.showToast('请填写商品数量')
        return
      }
    }

    wx.navigateTo({
      url: '../../pages/order2/order2?formData='+JSON.stringify(this.data.formData)
    })
  }
})